import requests
import json
from typing import Dict

def get_regs(ip: str, port: int = 5003) -> Dict:
    """
    获取呼叫盒的状态信息
    
    Args:
        ip: 呼叫盒的IP地址
        port: 呼叫盒的端口号，默认为5003
        
    Returns:
        包含设备信息和寄存器值的字典
        
    Raises:
        requests.RequestException: 当HTTP请求失败时
        ValueError: 当返回的数据格式不正确时
    """
    try:
        url = f"http://{ip}:{port}/cmd/get_regs"
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        data = response.json()
        if not all(key in data for key in ["dev_id", "model", "regs"]):
            raise ValueError("返回的数据格式不正确，缺少必要的字段")
        return data
        
    except requests.RequestException as e:
        raise requests.RequestException(f"获取呼叫盒状态失败: {str(e)}")
    except json.JSONDecodeError:
        raise ValueError("返回的数据不是有效的JSON格式")


def set_regs(ip: str, reg_values: Dict[int, int], port: int = 5003) -> Dict:
    """
    修改呼叫盒的寄存器值
    
    Args:
        ip: 呼叫盒的IP地址
        reg_values: 要修改的寄存器ID和值的字典，如 {20: 0, 21: 2}
        port: 呼叫盒的端口号，默认为5003
        
    Returns:
        包含操作结果的字典
        
    Raises:
        ValueError: 当寄存器ID或值超出有效范围时
        requests.RequestException: 当HTTP请求失败时
    """
    for reg_id, value in reg_values.items():
        if not (10 <= reg_id <= 29):
            raise ValueError(f"寄存器ID {reg_id} 超出有效范围[10,29]")
        if not (0 <= value <= 29):
            raise ValueError(f"寄存器值 {value} 超出有效范围[0,29]")
    
    try:
        params = [f"reg{reg_id}={value}" for reg_id, value in reg_values.items()]
        params_str = "&".join(params)
        url = f"http://{ip}:{port}/cmd/set_regs?{params_str}"
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        data = response.json()
        if not all(key in data for key in ["Code", "Msg"]):
            raise ValueError("返回的数据格式不正确，缺少必要的字段")
        return data
        
    except requests.RequestException as e:
        raise requests.RequestException(f"修改呼叫盒寄存器失败: {str(e)}")
    except json.JSONDecodeError:
        raise ValueError("返回的数据不是有效的JSON格式")
    
def blink_led(ip: str, duration: float = 1.5, port: int = 5003) -> None:
    try:
        
        # 设置LED为快闪，将flag设置为1
        result = set_regs(ip, {12:1}, port)

        time.sleep(duration)
        
        # 设置LED为常亮，将flag设置为0
        result = set_regs(ip, {12:0}, port)

    except Exception as e:
        print(f"{btn_name}LED闪烁过程中出错: {str(e)}")
